﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Zocono.Infrastructure.Common;
using Zocono.WCS.Admin.Common;
using Zocono.WCS.Admin.Models.User;
using Zocono.WCS.Admin.Models.WorkTaskManager;
using Zocono.WCS.Application.AppConfigureManage;
using Zocono.WCS.Application.AppTraces;
using Zocono.WCS.Domain.EntityInfo;
using Zocono.WCS.Infrastructure.ApllicationDto.Enums;
using Zocono.WCS.Infrastructure.ApllicationDto.WCSTaskDto;

namespace Zocono.WCS.Admin.Controllers.WorkTaskManagerMoudle
{
    [BasicAuth]
    public class WorkTaskInfoController : BaseController
    {
        private readonly WorkTaskInfoApp _workTaskInfoApp;
        private readonly ILogUtil _logUtil;
        private readonly TaskRouteDetailRecordInfoApp _taskRouteDetailRecordInfoApp;

        public WorkTaskInfoController(WorkTaskInfoApp workTaskInfoApp, ILogUtil logUtil, TaskRouteDetailRecordInfoApp taskRouteDetailRecordInfoApp, IMemoryCache memoryCache, TracesApp tracesApp, IHttpContextAccessor httpContextAccessor) : base(memoryCache, tracesApp, httpContextAccessor)
        {
            this._workTaskInfoApp = workTaskInfoApp;
            _logUtil = logUtil;
            this._taskRouteDetailRecordInfoApp = taskRouteDetailRecordInfoApp;
        }

        public IActionResult Index()
        {
            return View();
        }

        public async Task<ActionResult> WorkTaskInfoAsync()
        {
            var taskSearchData = new WorkTaskInfoSearchData();
            //await AddTracesInfo();
            return View(taskSearchData);
        }
        public async Task<ActionResult> EditorWorkTaskInfo(long id)
        {
            var workTaskInfo = new WorkTaskInfo();
          
            if (id != 0)
                workTaskInfo = await _workTaskInfoApp.GetWorkTaskByIdAsync(id);
          
            return View(workTaskInfo);
        }

        public async Task<JsonResult> GetAllWorkTaskInfoAsync()
        {
            var where = new QueryWorkTaskInfoDto();
            where.PageIndex = (Start / Length) + 1;
            where.PageSize = Length;
            where.FromStation = Request.Form["FromStation"].ToString();//起 始 工 位
            where.ToStation = Request.Form["ToStation"].ToString();//目 标 工 位
            where.WmsFromStation = Request.Form["WmsFromStation"].ToString();//WMS起始工位
            where.WmsToStation = Request.Form["WmsToStation"].ToString();//WMS目标工位
            where.WmsFromPosition = Request.Form["WmsFromPosition"].ToString();//WMS起始位置
            where.WmsToPosition = Request.Form["WmsToPosition"].ToString();//WMS目标位置
            where.PalletCode = Request.Form["PalletCode"].ToString();//托 盘 编 码
            where.RouteInfo = Request.Form["RouteInfo"].ToString();//巷道


            where.CurrentDispatchType = Request.Form["CurrentDispatchType"].ToInt32();//当前调度类型
            var TaskCode = Request.Form["TaskCode"].ToInt32();//任务 编 码
            if (TaskCode != 0)
            {
                where.TaskCode = TaskCode;
            }
            var WmsTaskCode = Request.Form["WmsTaskCode"].ToInt32();//WMS任务编码
            if (WmsTaskCode != 0)
            {
                where.WmsTaskCode = WmsTaskCode;
            }
            var TaskType = Request.Form["TaskType"].ToInt32();//任 务 类 型
            if (TaskType != -1)
            {
                where.TaskType = TaskType;
            }
            var TaskState = Request.Form["TaskState"].ToInt32();//工 作 状 态
            if (TaskState != -1)
            {
                where.TaskState = TaskState;
            }
            var TaskProcessState = Request.Form["TaskProcessState"].ToInt32();//任务处理状态
            if (TaskProcessState != -1)
            {
                where.TaskProcessState = TaskProcessState;
            }
            var UploadWmsState = Request.Form["UploadWmsState"].ToInt32();
            if (UploadWmsState != -1)
            {
                where.UploadWmsState = UploadWmsState;
            }

            where.StarTime = Request.Form["startTime"];//创建时间 开始
            where.EndTime = Request.Form["endTime"];//创建时间 结束
            var workTaskInfo = await _workTaskInfoApp.GetPagedWorkTaskInfoAsync(where);
            var workTaskPageDatas = new List<WorkTaskInfoPageData>();
            if (workTaskInfo != null && workTaskInfo.Result != null && workTaskInfo.Result.Count > 0)
            {
                foreach (var item in workTaskInfo.Result)
                {
                    workTaskPageDatas.Add(new WorkTaskInfoPageData()
                    {
                        ID = item.ID,
                        RouteID = item.RouteID,
                        FromStation = item.FromStation,
                        ToStation = item.ToStation,
                        Priority = item.Priority,
                        PalletCode = item.PalletCode,
                        TaskCode = item.TaskCode,
                        TaskProcessState = (int)item.TaskProcessState,
                        TaskState = (int)item.TaskState,
                        TaskType = (int)item.TaskType,
                        SaveTime = item.SaveTime,
                        UpdateTime = item.UpdateTime,
                        WmsTaskCode = item.WmsTaskCode,
                        DependWmsTaskCode = item.DependWmsTaskCode,
                        WmsFromStation = item.WmsFromStation,
                        WmsFromPosition = item.WmsFromPosition.ToString() + "->" + item.WmsToPosition.ToString(),
                        WmsToStation = item.WmsToStation,
                        WmsToPosition = item.WmsToPosition,
                        CurrentRounteDetailID = item.CurrentRounteDetailID,
                        CurrentDetailTaskState = (int)item.CurrentDetailTaskState,
                        CurrentDispatchType = (int)item.CurrentDispatchType,
                        CurrentFromEquipment = item.CurrentFromEquipment,
                        CurrentFromCargo = item.CurrentFromCargo,
                        CurrentToEquipment = item.CurrentToEquipment,
                        CurrentToCargo = item.CurrentToCargo,
                        CurrentCreateTime = item.CurrentCreateTime,
                        CurrentUpdateTime = item.CurrentUpdateTime,
                        UploadWmsState = (int)item.UploadWmsState,
                        UploadWmsTime = item.UploadWmsTime
                    });
                }
            }
            var pageData = new TableData<WorkTaskInfoPageData>(Draw, workTaskInfo.Total, workTaskInfo.Total, workTaskPageDatas);

            //await AddTracesInfo(5, 0, "获取任务列表信息");
            return Json(pageData);
        }

        public ActionResult TaskRouteDetailInfoAsync(long id)
        {
            ViewBag.Id = id;
            //await AddTracesInfo();
            return View();
        }


        public async Task<JsonResult> GetTaskDetailInfoByIdAsync(long id)
        {
            var taskInfos = await _taskRouteDetailRecordInfoApp.GetTaskRouteDetailRecordInfoAsync(id);

            var taskPageDatas = new List<TaskRouteDetailInfoPageData>();
            if (taskInfos != null && taskInfos.Count > 0)
            {
                foreach (var item in taskInfos)
                {
                    taskPageDatas.Add(new TaskRouteDetailInfoPageData()
                    {
                        ID = item.ID,
                        TaskID = item.TaskID,
                        RouteDetailID = item.RouteDetailID,
                        DetailTaskState = item.DetailTaskState,
                        DispatchType = item.DispatchType,
                        FromEquipment = item.FromEquipment,
                        FromCargo = item.FromCargo,
                        ToCargo = item.ToCargo,
                        ToEquipment = item.ToEquipment,
                        CreateTime = item.CreateTime,
                        UpdateTime = item.UpdateTime,
                    });
                }
            }
            var pageData = new TableData<TaskRouteDetailInfoPageData>(Draw, taskPageDatas.Count, taskPageDatas.Count, taskPageDatas);

            //await AddTracesInfo(5, 0, "获取task详情");
            return Json(pageData);
        }

        /// <summary>
        /// 复位任务
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> ResetWorkTaskStatusAsync()
        {
            var id = Request.Form["id"].ToInt64();
            bool result;
            string msg;
            try
            {
                var workTask = await _workTaskInfoApp.GetWorkTaskByIdAsync(id);
                if (workTask != null)
                {
                    if (workTask.TaskState == EnumTaskState.Finish || workTask.TaskState == EnumTaskState.ManualFinish || workTask.TaskState == EnumTaskState.Cancel)
                    {
                        result = false;
                        msg = "该任务状态不能重置";
                    }
                    else if (workTask.CurrentDetailTaskState != EnumDetailTaskState.Executing)
                    {
                        result = false;
                        msg = "该任务节点状态不能重置";
                    }
                    else if (workTask.CurrentDispatchType != EnumDispatchType.SC_UP && workTask.CurrentDispatchType != EnumDispatchType.SC_DOWN && workTask.CurrentDispatchType != EnumDispatchType.SC_MOVE)
                    {
                        result = false;
                        msg = "该业务任务不能重置";
                    }
                    //执行中并且当前节点状态为未执行才能 重置任务状态
                    else
                    {
                        workTask.CurrentDetailTaskState = EnumDetailTaskState.Init;
                        result = await _workTaskInfoApp.UpdataWorkTaskByTaskAsync(workTask);
                        msg = result ? "成功" : "失败";
                    }
                }
                else
                {
                    result = false;
                    msg = "任务不存在";
                }
            }
            catch (Exception e)
            {
                result = false;
                msg = e.Message;
            }
            await AddTracesInfo(3, 0, "重置任务状态");
            return CreateJsonGetResult(result, msg);
        }


        /// <summary>
        /// 置顶任务
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> TopWorkTaskStatusAsync()
        {
            var id = Request.Form["id"].ToInt64();
            bool result;
            string msg;
            try
            {
                var workTask = await _workTaskInfoApp.GetWorkTaskByIdAsync(id);
                if (workTask != null)
                {
                    if (workTask.TaskState == EnumTaskState.Finish || workTask.TaskState == EnumTaskState.ManualFinish || workTask.TaskState == EnumTaskState.Cancel)
                    {
                        result = false;
                        msg = "该任务状态不能置顶";
                    }
                    else if (workTask.CurrentDetailTaskState != EnumDetailTaskState.Init)
                    {
                        result = false;
                        msg = "该任务节点状态不能置顶";
                    }
                    else if (workTask.CurrentDispatchType == EnumDispatchType.Planar)
                    {
                        result = false;
                        msg = "平面设备任务不能置顶";
                    }
                    //执行中并且当前节点状态为未执行才能 重置任务状态
                    else
                    {
                        workTask.Priority = 9999;
                        result = await _workTaskInfoApp.UpdataWorkTaskByTaskAsync(workTask);
                        msg = result ? "成功" : "失败";
                    }
                }
                else
                {
                    result = false;
                    msg = "任务不存在";
                }
            }
            catch (Exception e)
            {
                result = false;
                msg = e.Message;
            }
            await AddTracesInfo(3, 0, "置顶任务状态");
            return CreateJsonGetResult(result, msg);
        }

        /// <summary>
        /// 置顶任务
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> CanselTopWorkTaskStatusAsync()
        {
            var id = Request.Form["id"].ToInt64();
            bool result;
            string msg;
            try
            {
                var workTask = await _workTaskInfoApp.GetWorkTaskByIdAsync(id);
                if (workTask != null)
                {
                    if (workTask.TaskState == EnumTaskState.Finish || workTask.TaskState == EnumTaskState.ManualFinish || workTask.TaskState == EnumTaskState.Cancel || workTask.TaskState == EnumTaskState.Executing)
                    {
                        result = false;
                        msg = "该任务状态不能取消置顶";
                    }
                    else if (workTask.CurrentDetailTaskState == EnumDetailTaskState.Executing)
                    {
                        result = false;
                        msg = "该任务节点状态不能取消置顶";
                    }
                    //执行中并且当前节点状态为未执行才能 重置任务状态
                    else
                    {
                        workTask.Priority = 1;
                        result = await _workTaskInfoApp.UpdataWorkTaskByTaskAsync(workTask);
                        msg = result ? "成功" : "失败";
                    }
                }
                else
                {
                    result = false;
                    msg = "任务不存在";
                }
            }
            catch (Exception e)
            {
                result = false;
                msg = e.Message;
            }
            await AddTracesInfo(3, 0, "置顶任务状态");
            return CreateJsonGetResult(result, msg);
        }

        /// <summary>
        /// 删除任务
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> DelWorkTaskStatusAsync()
        {
            var id = Request.Form["id"].ToInt64();
            var palletCode = Request.Form["palletCode"].ToString();
            var wmsTaskCode = Request.Form["wmsTaskCode"].ToString();

            bool result;
            string msg;
            try
            {
                var workTask = await _workTaskInfoApp.GetWorkTaskByIdAsync(id);
                if (workTask != null)
                {
                    if (workTask.TaskType == EnumTaskType.STG)
                    {
                        workTask.TaskProcessState = EnumTaskProcessState.PlanerCompleted;
                    }
                    else
                    {
                        workTask.TaskProcessState = EnumTaskProcessState.ScUnloaded;
                    }
                    workTask.TaskState = EnumTaskState.ManualFinish;
                    workTask.CurrentDetailTaskState = EnumDetailTaskState.Finish;
                    workTask.CurrentUpdateTime = DateTime.Now;
                    result = await _workTaskInfoApp.UpdataWorkTaskByTaskAsync(workTask);
                    result = await _workTaskInfoApp.DelWorkTaskAsync(id);
                    //result = await _workTaskInfoApp.DelWorkTaskAsync(id);
                    msg = result ? $"成功" : $"失败";
                    if (result)
                    {
                        await AddTracesInfo(4, 0, $"删除托盘【{palletCode}】任务【{wmsTaskCode}】{msg}");
                    }
                }
                else
                {
                    result = false;
                    msg = $"任务不存在";
                }
            }
            catch (Exception e)
            {
                result = false;
                msg = $"{palletCode}" + e.Message;
            }
            return CreateJsonGetResult(result, msg);
        }

        /// <summary>
        /// 手动任务
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> CompleteWorkTaskStatusAsync()
        {
            var id = Request.Form["id"].ToInt64();
            bool result;
            string msg;
            try
            {
                var workTask = await _workTaskInfoApp.GetWorkTaskByIdAsync(id);
                if (workTask != null)
                {
                    result = false;
                    msg = "当前不是堆垛机作业";
                    //上架完成，更新状态到WMS，以及完成任务
                    if (workTask.TaskState != EnumTaskState.Finish && workTask.TaskState != EnumTaskState.ManualFinish)
                    {
                        //平面设备另作
                        if (workTask.CurrentDispatchType == EnumDispatchType.SC_UP || workTask.CurrentDispatchType == EnumDispatchType.SC_MOVE || workTask.CurrentDispatchType == EnumDispatchType.Planar)
                        {
                            if (workTask.CurrentDispatchType == EnumDispatchType.Planar)
                            {
                                workTask.TaskProcessState = EnumTaskProcessState.PlanerCompleted;
                            }
                            else
                            {
                                workTask.TaskProcessState = EnumTaskProcessState.ScUnloaded;
                            }
                            workTask.TaskState = EnumTaskState.ManualFinish;
                            workTask.CurrentDetailTaskState = EnumDetailTaskState.Finish;
                            workTask.CurrentUpdateTime = DateTime.Now;
                            workTask.UploadWmsState = EnumUploadWmsState.Succeed;

                            HeaderResult<bool> headerResult = new();
                            //更新状态到WMS，以及完成任务
                            //临时修改
                            ////WMSApiDomain.WebApi.HeaderResult
                            if (workTask.CurrentDispatchType == EnumDispatchType.Planar)
                                headerResult = await SimpleApiClient.GetAsync<HeaderResult<bool>>(Parameters.WCSNoticeTaskAutoComplete, new { taskCode = workTask.WmsTaskCode, containercode = workTask.PalletCode, equipment = workTask.CurrentToEquipment });
                            else
                                headerResult = await SimpleApiClient.GetAsync<HeaderResult<bool>>(Parameters.WCSNoticeTaskAutoComplete, new { taskCode = workTask.WmsTaskCode, containercode = workTask.PalletCode, equipment = workTask.CurrentToCargo });

                            //bool headerResult = await SimpleApiClient.GetAsync<bool>(Parameters.WCSNoticeTaskAutoComplete, new { taskCode = workTask.WmsTaskCode});
                            if (headerResult.IsSucceed)
                            {
                                result = await _workTaskInfoApp.UpdataWorkTaskByTaskAsync(workTask);
                                msg = result ? "成功" : "失败";
                            }
                            else
                            {
                                await AddTracesInfo(3, 0, "WMS返回结果为失败");
                                msg = result ? "成功" : $"WMS返回结果{headerResult.Message}";
                            }
                        }
                        //下架完成，更新状态到WMS，以及更新状态及路径
                        if (workTask.CurrentDispatchType == EnumDispatchType.SC_DOWN)
                        {
                            workTask.TaskProcessState = EnumTaskProcessState.ScUnloaded;
                            workTask.CurrentDetailTaskState = EnumDetailTaskState.Finish;

                            var nextroutedetail = await _workTaskInfoApp.GetNextRouteDetailInfoByIdAsync(workTask.CurrentRounteDetailID);
                            workTask.TaskProcessState = EnumTaskProcessState.ScUnloaded;
                            workTask.CurrentRounteDetailID = nextroutedetail.ID;
                            workTask.CurrentDetailTaskState = EnumDetailTaskState.Init;
                            workTask.CurrentDispatchType = nextroutedetail.DispatchType;
                            workTask.CurrentFromEquipment = nextroutedetail.FromEquipment;
                            workTask.CurrentFromCargo = nextroutedetail.FromCargo;
                            workTask.CurrentToEquipment = nextroutedetail.ToEquipment;
                            workTask.CurrentToCargo = nextroutedetail.ToCargo;
                            workTask.CurrentCreateTime = DateTime.Now;
                            workTask.CurrentUpdateTime = new DateTime(1900, 1, 1);

                            //释放货位
                            HeaderResult<bool> headerResult = await SimpleApiClient.GetAsync<HeaderResult<bool>>(Parameters.WCSNoticePalltetArriveDoEquipment, new { taskCode = workTask.WmsTaskCode });
                            if (headerResult.IsSucceed)
                            {
                                result = await _workTaskInfoApp.UpdataWorkTaskByTaskAsync(workTask);
                                msg = result ? "成功" : "失败";
                            }
                            else
                            {
                                await AddTracesInfo(3, 0, "WMS返回结果为失败");
                                msg = result ? "成功" : $"WMS返回结果为{headerResult.Message}";
                            }
                        }
                    }
                    else
                    {
                        if ((workTask.TaskState == EnumTaskState.Finish || workTask.TaskState == EnumTaskState.ManualFinish) && workTask.UploadWmsState == EnumUploadWmsState.Failed)
                        {
                            if (workTask.CurrentDispatchType == EnumDispatchType.Planar)
                            {
                                workTask.TaskProcessState = EnumTaskProcessState.PlanerCompleted;
                            }
                            else
                            {
                                workTask.TaskProcessState = EnumTaskProcessState.ScUnloaded;
                            }
                            workTask.TaskState = EnumTaskState.ManualFinish;
                            workTask.CurrentDetailTaskState = EnumDetailTaskState.Finish;
                            workTask.CurrentUpdateTime = DateTime.Now;
                            workTask.UploadWmsState = EnumUploadWmsState.Succeed;

                            HeaderResult<bool> headerResult = new();    
                            //更新状态到WMS，以及完成任务
                            //临时修改
                            ////WMSApiDomain.WebApi.HeaderResult
                            if (workTask.CurrentDispatchType == EnumDispatchType.Planar)
                                 headerResult = await SimpleApiClient.GetAsync<HeaderResult<bool>>(Parameters.WCSNoticeTaskAutoComplete, new { taskCode = workTask.WmsTaskCode, containercode = workTask.PalletCode, equipment = workTask.CurrentToEquipment });
                            else
                                headerResult = await SimpleApiClient.GetAsync<HeaderResult<bool>>(Parameters.WCSNoticeTaskAutoComplete, new { taskCode = workTask.WmsTaskCode, containercode = workTask.PalletCode, equipment = workTask.CurrentToCargo });
                            //bool headerResult = await SimpleApiClient.GetAsync<bool>(Parameters.WCSNoticeTaskAutoComplete, new { taskCode = workTask.WmsTaskCode});
                            if (headerResult.IsSucceed)
                            {
                                result = await _workTaskInfoApp.UpdataWorkTaskByTaskAsync(workTask);
                                msg = result ? "成功" : "失败";
                            }
                            else
                            {
                                await AddTracesInfo(3, 0, "WMS返回结果为失败");
                                msg = result ? "成功" : $"WMS返回结果{headerResult.Message}";
                            }
                        }
                    }
                }
                else
                {
                    result = false;
                    msg = "任务不存在";
                }
            }
            catch (Exception e)
            {
                result = false;
                msg = "WMS返回结果为异常";
            }
            await AddTracesInfo(3, 0, "手动完成任务");
            return CreateJsonGetResult(result, msg);
        }

        /// <summary>
        /// 修改任务
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> UpWorkTaskStatusAsync()
        {
            var id = Request.Form["id"].ToInt64();
            var taskState = Request.Form["taskState"].ToString();
            var crrentDetailTaskState = Request.Form["currentDetailTaskState"].ToString();
            var currentToCargo = Request.Form["currentToCargo"].ToString();
            var currentToEquipment = Request.Form["currentToEquipment"].ToString();
            bool result;
            string msg;
            try
            {
                var workTask = await _workTaskInfoApp.GetWorkTaskByIdAsync(id);
                var palletCode = workTask.PalletCode;
                if (workTask != null)
                {
                    if(taskState== "Executing")
                    workTask.TaskState = EnumTaskState.Executing;
                    else if(taskState == "Initial")
                        workTask.TaskState = EnumTaskState.Initial;
                    else if (taskState == "Finish")
                        workTask.TaskState = EnumTaskState.Finish;
                    else if (taskState == "ManualFinish")
                        workTask.TaskState = EnumTaskState.ManualFinish;
                    else if (taskState == "Cancel")
                        workTask.TaskState = EnumTaskState.Cancel;



                    if (crrentDetailTaskState == "Executing")
                        workTask.CurrentDetailTaskState = EnumDetailTaskState.Executing;
                    else if (crrentDetailTaskState == "Finish")
                        workTask.CurrentDetailTaskState = EnumDetailTaskState.Finish;
                    else if (crrentDetailTaskState == "Init")
                        workTask.CurrentDetailTaskState = EnumDetailTaskState.Init;
                



                    workTask.CurrentToCargo = currentToCargo;
                    workTask.CurrentToEquipment = currentToEquipment;
                    workTask.CurrentUpdateTime = DateTime.Now;
                    
                    result = await _workTaskInfoApp.UpdataWorkTaskByTaskAsync(workTask);
                  
                    msg = result ? $"成功{palletCode}" : $"失败{palletCode}";

                }
                else
                {
                    result = false;
                    msg = $"{palletCode}任务不存在";
                }
            }
            catch (Exception e)
            {
                result = false;
                msg = $"{id}" + e.Message;
            }

            return CreateJsonGetResult(result, msg);
        }
        public ActionResult MonitorWorkTaskInfoAsync()
        {
            return View();
        }
        /// <summary>
        /// 模拟交互获取WMS任务
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> GetWorkTaskFromMonitorAsync()
        {
            var user = GetUserModel();
            if (user == null || user.RoleId != 1)
            {
                return CreateJsonGetResult(false, "您的账号无此权限！");
            }
            var containerCode = Request.Form["containerCode"].ToString();
            var equipment = Request.Form["equipment"].ToString();

            var res = await _workTaskInfoApp.GetWarehouseWMSTaskAsync(containerCode, equipment);
            bool result = false;
            string msg = "失败！";
            if (res)
            {
                result = true;
                msg = "成功！";
            }

            return CreateJsonGetResult(result, msg);
        }

    }
}
